/** H5Editor:1.3.31@license:MIT
Mail:eqphp_framework@126.com
https://gitee.com/eqphp/h5editor **/
const AE_text_tag = ['span', 'em', 'a', 'b', 'i'];
const AE_head_tag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
const AE_block_tag = ['p', 'table', 'ol', 'ul', 'pre', 'blockquote'];
let AE_editor, AE = {l1: 0, l2: 0, text: '', tag: '', mid_tag: '', top_tag: ''};

$(function () {
    document.execCommand('defaultParagraphSeparator', false, 'p');
    $(AE_color_board).each(function (i, c) {
        $('.color_board').append('<b style="background-color:#' + c + ';"></b>');
    });

    AE_editor = $('.AE_article');
    AE_editor.mouseup(function () {
        AE_focus_sure();
    }).keyup(function () {
        AE_focus_sure();
    }).on('paste', function () {
        return false;
    }).focus();

    AE_editor.pastableContenteditable();
    AE_editor.on('pasteImage', function (e, data) {
        AE_upload(data.blob, 'photo.png', function (response) {
            if (response.error === 0) {
                AE_insert_block(AE_build_html('img', AE_path['photo'] + response.data, true));
            }
        });
    }).on('pasteText', function (e, data) {
        let html = '';
        if (['pre', 'blockquote'].includes(AE.tag)) {
            html += AE.ele.innerHTML.substr(0, AE.l1);
            html += data.text + AE.ele.innerHTML.substr(AE.l2);
            $('#_' + AE.node_id).html(html);
        } else {
            let text = data.text.split('\n');
            if (text.length > 1) {
                for (let i=0;i<text.length;i++) {
                    if ($.trim(text[i]).length) {
                        html += AE_build_html('p', $.trim(text[i]), true);
                    }
                }
                AE_insert_block(html);
            } else {
                if (AE.ele === undefined) {
                    html += text[0];
                } else {
                    html += AE.ele.innerHTML.substr(0, AE.l1);
                    html += text[0] + AE.ele.innerHTML.substr(AE.l2);
                }
                $('#_' + AE.node_id).html(html);
            }
        }
    }).on('pasteImageError', function (e, data) {
        console.log('paste error: ' + data.message);
    });

    $('#AE_editor svg').mouseenter(function(){
        let svg = $(this);
        svg.attr('fill', AE_color[1]);
        AE.action = svg.attr('_action');
        if (['color', 'header', 'emoji'].includes(AE.action)) {
            let d = dialog({
                padding: 10,
                follow: svg[0],
                quickClose: true,
                align: 'bottom',
                content: $('#'+AE.action).html()
            }).show();
            $('.ui-popup-backdrop').remove();
            $('.ui-dialog').live('mouseleave', function () {
                d.remove();
            });
        }
    }).click(function(){
        AE.action = $(this).attr('_action');
        if (['pre','blockquote'].includes(AE.action)) {
            if (AE.tag === AE.action) {
                AE_insert_block(AE_build_html('p', AE.ele.innerText));
            } else {
                AE_insert_block(AE_build_html(AE.action, AE.text, true));
            }
        }
        if (AE_head_tag.includes(AE.tag) && AE.action==='header') {
            AE_insert_block(AE_build_html('p', AE.ele.innerText));
            AE.ele.remove();
        }
        if (['b', 'i'].includes(AE.action)) {
            if (AE.tag === AE.action) {
                AE_insert_text(AE_build_html('span', AE.ele.innerHTML));
            } else if (AE.text.length && AE.text.length === AE.l2 - AE.l1) {
                if (AE.tag === 'p') {
                    AE.ele.innerHTML = AE_divide_text(AE.action);
                }
                if (['span', 'b', 'i', 'em'].includes(AE.tag)) {
                    AE_insert_text(AE_divide_text(AE.action));
                }
            }
        }
        if (['ol', 'ul'].includes(AE.action)) {
            if (AE.tag === 'li') {
                $('#__' + AE.node_id).after(AE_build_html('p', AE.ele.innerText));
                AE.ele.remove();
            } else {
                let li = '';
                if (AE.text.length) {
                    let text = AE.text.split('\n');
                    for (let i = 0; i < text.length; i++) {
                        if ($.trim(text[i]).length) {
                            li += AE_build_html('li', $.trim(text[i]), true);
                        }
                    }
                } else {
                    li += AE_build_html('li', '', true);
                }
                AE_insert_block(AE_build_html(AE.action, '\n' + li));
            }
        }
        if (['table', 'a', 'map'].includes(AE.action)) {
            if (AE.action === 'a' && AE.tag === 'a') {
                AE_insert_text(AE_build_html('span',AE.ele.innerHTML));
                return;
            }
            let dict = {'table': '表格', 'a': '超链接', 'map': '地图'};
            dialog({
                width: 360,
                okValue: '插入',
                autofocus: false,
                title: '插入' + dict[AE.action],
                content: $('#' + AE.action).html(),
                ok: function () {
                    if (AE.action === 'a') {
                        AE_insert_link(this);
                    } else if (AE.action === 'table') {
                        AE_insert_table(this);
                    } else {
                        AE_insert_map(this);
                    }
                    return false;
                }
            }).showModal();
            if (AE.text.length && AE.action === 'a') {
                $('input[name="url"]').focus();
                $('input[name="a"]').val(AE.text);
            } else {
                $('input[name="' + AE.action + '"]').focus();
            }
        }
        if (AE.action === 'color' && ['p', 'li', 'td', 'em'].includes(AE.tag)) {
            if (AE.tag === 'em') {
                AE_insert_text(AE_build_html('span',AE.ele.innerHTML));
            } else {
                $('#_' + AE.node_id).removeAttr('class');
            }
            AE_merge_tag();
        }
        if (['html', 'text'].includes(AE.action)) {
            let AE_text = $('#AE_article');
            if (AE.action === 'html') {
                AE_editor.hide();
                $(this).attr('_action', 'text');
                AE_text.val(AE_editor.html().replace(/\sid="_[_.]?\d{13}"/g,'')).show();
            } else {
                AE_text.hide();
                $(this).attr('_action', 'html');
                AE_editor.html(AE_text.val()).show();
            }
        }
        if (['photo','video','archive'].includes(AE.action)) {
            $('input[name="' + AE.action + '"]').click();
        }
        if (AE.action === 'hr') {
            AE_insert_block('<hr>\n<p></p>\n');
        }
    }).mouseleave(function(){
        $(this).attr('fill', AE_color[0]);
    });

    $('.color_board b').live('click', function () {
        let color = 'fc' + $(this).index();
        if (['p', 'span', 'em'].includes(AE.tag)) {
            if (AE.text.length && AE.text.length === AE.l2 - AE.l1) {
                AE_insert_text(AE_divide_text('', AE_build_html('em', AE.text, false, color)));
            }
        } else if (['li', 'td'].includes(AE.tag)) {
            $('#_' + AE.node_id).removeClass().addClass(color);
        }
        $('.ui-popup').remove();
    });

    $('.header_list *').live('click', function () {
        $('.ui-popup').remove();
        let allow = AE_head_tag.concat('p');
        let container = $((allow.includes(AE.tag) ? '#_' : '#__') + AE.node_id);
        let src_tag = container[0].tagName.toLowerCase();
        let dest_tag = $(this)[0].tagName.toLowerCase();
        if (allow.includes(src_tag)) {
            dest_tag = dest_tag === src_tag ? 'p' : dest_tag;
            container.after(AE_build_html(dest_tag, container.text(), true, '_' + AE.node_id)).remove();
        }
    });

    $('.emoji_list h3 span').live('click', function () {
        $('.emoji_list p').hide();
        $('.emoji_list h3 span').removeClass('select');
        $(this).addClass('select');
        let key = $(this).index();
        let html = '', emoji = AE_emoji[key];
        $(emoji.name).each(function (i, name) {
            html += '<img src="' + AE_path.emoji + emoji.dir + '/' + name + '.' + emoji.ext + '">';
            if ((i + 1) % 10 === 0) {
                html += '<br>';
            }
        });
        $('.emoji_list .emoji_' + key).html(html).show();
    });

    $('.emoji_list img').live('click', function () {
        $('.ui-popup').remove();
        AE_insert_block(AE_build_html('img', $(this).attr('src')));
    });

    $('input[type="file"]').change(function () {
        if ($(this).val()) {
            let file = $(this)[0].files[0];
            let type = $(this).attr('name');
            let src = URL.createObjectURL(file);
            if (type === 'archive') {
                let suffix = file.name.substr(file.name.lastIndexOf('.') + 1, 3).toLowerCase();
                suffix = ['doc', 'xls', 'ppt', 'pdf', 'txt'].includes(suffix) ? suffix : 'def';
                let html = '<a class="icon ' + suffix + '" href="' + src + '">' + file.name + '</a>';
                AE_insert_block(AE_build_html('p', html, true));
            } else {
                let tag = type === 'photo' ? 'img' : type;
                AE_insert_block(AE_build_html(tag, src));
            }
        }
    });

    $('#message_advice').click(function () {
        dialog({
            width: 360,
            okValue: '提交',
            autofocus: false,
            title: '留言建议',
            content: $('#guest_book').html(),
            ok: function () {
                let postData = {contact: $('input[name="contact"]:last').val(),
                    message: $('textarea[name="message"]:last').val()};
                if (postData.message.length > 3) {
                    $.post('/guest.php', postData, function () {
                        alert('非常感谢您的留言，我们会尽快与您联系给您答复。');
                    }, 'json');
                }
                return true;
            }
        }).showModal();
        $('input[name="contact"]').focus();
    });

});

function AE_focus_sure() {
    let select = window.getSelection();
    if (select.anchorOffset < select.focusOffset) {
        AE.l1 = select.anchorOffset;
        AE.l2 = select.focusOffset;
    } else {
        AE.l1 = select.focusOffset;
        AE.l2 = select.anchorOffset;
    }

    AE.mid_tag = '';
    AE.top_tag = '';
    AE.text = select.toString();
    AE.node_id = new Date().getTime();
    AE.ele = select.focusNode.parentElement;
    AE.tag = AE.ele.tagName.toLowerCase();
    if (!['div', 'tbody', 'tr'].includes(AE.tag)) {
        AE.ele.setAttribute('id', '_' + AE.node_id);
    }
    if (AE_text_tag.concat(['td', 'th', 'tr', 'li']).includes(AE.tag)) {
        AE_loop_node(AE.ele, AE.node_id);
    }

    //console.log(AE);
    $('svg[_action]').attr('fill', AE_color[0]);
    if (['pre', 'blockquote', 'a', 'b', 'i'].includes(AE.tag)) {
        AE_svg_color(AE.tag);
    }
    if (['li', 'td', 'em'].includes(AE.tag)) {
        AE_svg_color('color');
    }
    if (AE_head_tag.includes(AE.tag)) {
        AE_svg_color('header');
    }
    if (AE.tag === 'li') {
        AE_svg_color(AE.top_tag);
    }
}

function AE_loop_node(ele, node_id) {
    ele = ele.parentElement;
    let tmp_tag = ele.tagName.toLowerCase();
    if (['li', 'th', 'td'].includes(tmp_tag)) {
        AE.mid_tag = tmp_tag;
        ele.setAttribute('id', '_.' + node_id);
    }
    if (AE_block_tag.includes(tmp_tag)) {
        AE.top_tag = tmp_tag;
        ele.setAttribute('id', '__' + node_id);
        return;
    }
    AE_loop_node(ele, node_id);
}

function AE_svg_color(selector) {
    $('svg[_action="' + selector + '"]').attr('fill', AE_color[1]);
}

function AE_insert_link(dialog) {
    if (AE.tag.length) {
        let text, url;
        text = $('input[name="a"]:last').val();
        url = $('input[name="url"]:last').val();
        if (text.length < 1) {
            $('input[name="a"]').focus();
            return;
        }
        let html = '<a href="' + url + '">' + text + '</a>';
        AE_insert_text(AE_divide_text('a', html));
    }
    dialog.remove();
}

function AE_insert_table(dialog) {
    let row, col, head;
    row = parseInt($('input[name="table"]:last').val());
    col = parseInt($('input[name="column"]:last').val());
    head = $('select[name="head"]:last').val();
    if (isNaN(row) || row < 1) {
        $('input[name="table"]').focus();
        return;
    }
    if (isNaN(col) || col < 1) {
        $('input[name="column"]').focus();
        return;
    }
    let i, j, html;
    html = '<table><tbody>\n';
    for (i = 0; i < row; i++) {
        html += '<tr>';
        for (j = 0; j < col; j++) {
            html += ((head === 'both' && (i < 1 || j < 1)) || (head === 'top' && i < 1) || (head === 'left' && j < 1)) ? '<th></th>' : '<td></td>';
        }
        html += '</tr>\n';
    }
    html += '</tbody></table>\n';
    AE_insert_block(html);
    dialog.remove();
}

function AE_insert_map(dialog) {
    let text, position;
    text = $('input[name="map"]:last').val();
    position = $('input[name="position"]:last').val();
    if (position.length < 1 || position.indexOf(',') === -1) {
        $('input[name="position"]').focus();
        return;
    }
    text = text.replace(',') + ',' + position;
    AE_insert_block(AE_build_html('p', text, true, '_map'));
    dialog.remove();
}

function AE_insert_text(html){
    if (AE.tag.length) {
        if (AE_text_tag.includes(AE.tag)) {
            $('#_' + AE.node_id).after(html).remove();
        } else {
            $('#_' + AE.node_id).html(html);
        }
    }
    AE_merge_tag();
}

function AE_merge_tag() {
    if (AE.top_tag === 'p') {
        let pe = $('#__' + AE.node_id);
        pe.children().removeAttr('id');
        pe.html(pe.html().replace(/(<\/span><span>)|(<\/b><b>)|(<\/i><i>)/g, ''));
    }
}

function AE_insert_block(html) {
    let allow = AE_block_tag.concat(AE_head_tag);
    if (allow.includes(AE.tag)) {
        $('#_' + AE.node_id).after(html);
    } else if (allow.includes(AE.top_tag)) {
        $('#__' + AE.node_id).after(html);
    } else {
        AE_editor.append(html);
    }
}

/**
 * @return {string}
 */
function AE_divide_text(tag, value = '') {
    let html = '', text = AE.ele.innerHTML;
    if (AE.l1) {
        html += AE_build_html('span', text.substr(0, AE.l1));
    }
    html += (value.length) ? value : AE_build_html(tag, AE.text);
    if (AE.l2 < text.length) {
        html += AE_build_html('span', text.substr(AE.l2));
    }
    return html;
}

 /**
  * @return {string}
  */
 function AE_build_html(tag, value = '', isNewLine = false, attr = '') {
    let html = '<' + tag;
    if (attr.length) {
        if (attr.substr(0, 1) === '_') {
            html += ' id="' + attr + '"';
        } else {
            html += ' class="' + attr + '"';
        }
    }
    if (tag === 'video') {
        html += ' controls="controls" playsinline muted';
    }
    if (['img','video'].includes(tag)) {
        html += ' src="' + value + '">';
    } else {
        html += '>';
        if (value.length) {
            html += value;
        }
        html += '</' + tag + '>';
    }
    if (isNewLine) {
        html += '\n';
    }
    return html;
}

function AE_upload(blog, file_name, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open('POST', AE_path['upload'], true);
    xhr.timeout = 7000;
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            callback(JSON.parse(xhr.responseText));
        }
    };
    let form = new FormData();
    form.append('file', blog, file_name);
    xhr.send(form);
}